package com.example.mscluster.provider.user;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.mscluster.provider.user.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;


@RestController
public class UserProviderController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @GetMapping("/ping")
    public String info() {
        return "pong";
    }

    public static final String USER_KEY=RedisUtils.MS_PREFIX_KEY+"USER_ID";
    public static final String SPLIT_LINE="\n============\n";

//    @GetMapping("/consumer/user/all")
//    public String comsumerAllUser() {
//        String url="http://localhost:8080/provider/user/all";
////        ResponseEntity<JSONObject> requestObject = restTemplate.postForEntity(gspClientTokenUrl+ "/gsp-oauth/client/token",
////                requestEntity, JSONObject.class);
////        String body = JsonUtil.object2Json(bizObject);
////        String json = this.getRequestParams(body);
////        String url = dadaConfig.getApiPrefix() + requestPath;
//        System.out.println("http://localhost:8080/provider/user/all");
//        return OkHttpUtils.doGet(url);
//    }

    @GetMapping("/provider/user/all")
    public String providerAllUser() {
        String url="http://127.0.0.1:18082/provider/order/all";
        System.out.println("http request to order :"+url);
//        String orderContent=OkHttpUtils.doGet(url);
        String orderContent=orderFeignClient.getAllOrders();
        List<User> userList = userMapper.selectList(Wrappers.<User>lambdaQuery().select(User::getId, User::getEmail, User::getName, User::getAge));
        String value="";
        if (redisUtils.exists(USER_KEY))
        {
            value=redisUtils.get(USER_KEY).toString();
            System.out.println("key is :"+value);
        }
        else{
            value="User@"+userList.hashCode();
            redisUtils.set(USER_KEY,value);
            System.out.println("set the key :"+value);
        }
        String userString=GsonUtils.object2Json(userList);
        sleepRandomSec();
        return value+SPLIT_LINE+userString+SPLIT_LINE+orderContent;
    }

    public void sleepRandomSec() {
        Random rand = new Random();
        long sleepMill=Math.round(Math.abs(rand.nextGaussian()*100));
        try {
            System.out.println("sleep "+sleepMill+" millsec!");
            Thread.sleep(sleepMill);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
